﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Web.UI;

namespace MyClass.Client
{
    public class LoginHelper
    {
       
        /// <summary>
        /// CS访问登陆
        /// </summary>
        /// <param name="page">当前页</param>
        /// <returns></returns>
        public static string Login(Page page)
        {
            string indata = "num1=yemian";
            string outdata = "";
            string url = "http://localhost/sdf/bussiness.aspx";
            CookieContainer myCookieContainer = new CookieContainer();
            //新建一个CookieContainer来存放Cookie集合 
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            //新建一个HttpWebRequest 
            myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
            myHttpWebRequest.ContentLength = indata.Length;
            myHttpWebRequest.Method = "POST";

            myHttpWebRequest.CookieContainer = myCookieContainer;
            //设置HttpWebRequest的CookieContainer为刚才建立的那个myCookieContainer 
            Stream myRequestStream = myHttpWebRequest.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(indata);
            //把数据写入HttpWebRequest的Request流

            myStreamWriter.Close();
            myRequestStream.Close();
            //关闭打开对象 
            HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
            //新建一个HttpWebResponse 
            myHttpWebResponse.Cookies = myCookieContainer.GetCookies(myHttpWebRequest.RequestUri);
            //获取一个包含url的Cookie集合的CookieCollection 
            Stream myResponseStream = myHttpWebResponse.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("gb2312"));
            outdata = myStreamReader.ReadToEnd();
            //把数据从HttpWebResponse的Response流中读出 
            myStreamReader.Close();
            myResponseStream.Close();
            page.Response.Write(outdata);
            //显示"登录"

            //拿到了Cookie，再进行请求就能直接读取到登录后的内容了 
            myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            myHttpWebRequest.CookieContainer = myCookieContainer; //* 
            //刚才那个CookieContainer已经存有了Cookie,把它附加到HttpWebRequest中则能直接通过验证 
            myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
            myHttpWebResponse.Cookies = myCookieContainer.GetCookies(myHttpWebRequest.RequestUri);
            myResponseStream = myHttpWebResponse.GetResponseStream();
            myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("gb2312"));
            outdata = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            page.Response.Write("<br>" + outdata);




            try
            {
                // 要提交表单的URI字符串。
                string uriString = "http://localhost:1165/WebTest/MyLogin.aspx";

                ///////////////////////////////////////
                // 打开页面
                ///////////////////////////////////////
                WebClient webClient = new WebClient();
                byte[] responseData = webClient.DownloadData(uriString);
                string srcString = Encoding.UTF8.GetString(responseData);

                ///////////////////////////////////////
                // 填写页面并提交
                ///////////////////////////////////////
                webClient = new WebClient();
                webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

                // 获取页面的 VeiwState
                string viewStateFlag = "id=\"__VIEWSTATE\" value=\"";
                int i = srcString.IndexOf(viewStateFlag) + viewStateFlag.Length;
                int j = srcString.IndexOf("\"", i);
                string viewState = srcString.Substring(i, j - i);

                // 获取页面的 EventValidation
                string eventValidationFlag = "id=\"__EVENTVALIDATION\" value=\"";
                i = srcString.IndexOf(eventValidationFlag) + eventValidationFlag.Length;
                j = srcString.IndexOf("\"", i);
                string eventValidation = srcString.Substring(i, j - i);

                // 提交按钮的文本
                string submitButton = "登录";

                viewState = System.Web.HttpUtility.UrlEncode(viewState);
                eventValidation = System.Web.HttpUtility.UrlEncode(eventValidation);
                submitButton = System.Web.HttpUtility.UrlEncode(submitButton);

                // 要提交的字符串数据。格式形如:user=uesr1&password=123
                string postString = "userName=1&password=1" + "&loginButton=" + submitButton + "&__VIEWSTATE=" + viewState + "&__EVENTVALIDATION=" + eventValidation;
                // 将字符串转换成字节数组
                byte[] postData = Encoding.ASCII.GetBytes(postString);
                // 上传数据，返回页面的字节数组
                responseData = webClient.UploadData(uriString, "POST", postData);
                // 将返回的将字节数组转换成字符串(HTML);
                // ASP.NET 返回的页面一般是Unicode,如果是简体中文应使用 
                // Encoding.GetEncoding("GB2312").GetString(responseData)
                srcString = Encoding.UTF8.GetString(responseData);

                ///////////////////////////////////////
                // 分析返回的页面
                ///////////////////////////////////////
                // 
            }
            catch (WebException we)
            {
                string msg = we.Message;
            }

            return "";
        }

    }
}
